package com.example.demo.mq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by Hy on 2019/3/13.
 */
public class Sender {
    private static final int SEND_NUMBER = 2;
    public static void main(String[] args) {
        //1.connectionFactory是连接工厂，JMS用它创建连接
        ConnectionFactory connectionFactory;
        //2.Connection JMS客户端到JMS provider的链接
        Connection connection = null;
        //3Session 一个发送消息或者接收消息的线程
        Session session=null;
        //4.Destination 消息发送目的地，将消息发送给谁接收
        Destination destination;
        //5.MessageProducer 消息发送者
        MessageProducer messageProducer=null;
        //构造connectionFactory实例对象，此处采用ActiveMQ实现的jar
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"tcp://localhost:61616");

        try{
            //构造工厂得到连接对象
            connection = connectionFactory.createConnection();
            //启动
            connection.start();
            //获取操作连接
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            //创建一个queue名称为FirstQueue
            destination = session.createQueue("FirstQueue");
            //得到消息生产者【发送者】
            messageProducer = session.createProducer(destination);
            //设置不持久化，根据实际情况而定
            messageProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
            //构造消息，此处写死，项目就是参数或者方法获取
            sendMessage(session,messageProducer);
            session.commit();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(messageProducer!=null){
                    messageProducer.close();
                }
            }catch (Throwable ignore){
            }
            try{
                if (session!=null){
                    session.close();
                }
            }catch (Throwable ignore){
            }
            try{
                if(connection!=null){
                    connection.close();
                }
            }catch (Throwable ignore){
            }
        }
    }
    public static void sendMessage(Session session,MessageProducer producer) throws JMSException {
        for (int i =1;i<=SEND_NUMBER;i++){
            TextMessage textMessage = session.createTextMessage("ActiveMq发送的消息" + i);
            //发送消息到目的地方
            System.out.println("发送消息："+"ActiveMq发送的消息" + i);
            producer.send(textMessage);
        }
    }
}
